<?php

/**
 * Notes:WebSocket服务端
 * @Author szh
 * Class WS
 * 启动
 * php WS.php
 */
class WS
{
    private $ws = null;

    public function __construct()
    {
        $this->ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
        $this->http->set([
            'task_worker_num'    => 4,
        ]);
        $this->ws->on('open', [$this, "onOpen"]);
        $this->ws->on('message', [$this, "onMessage"]);
        $this->ws->on('task', [$this, "onTask"]);
        $this->ws->on('finish', [$this, "onFinish"]);
        $this->ws->on('close', [$this, "onClose"]);
        $this->ws->start();
    }
    public function onOpen($ws, $request){
        var_dump($request->fd, $request->get, $request->server);
        $ws->push($request->fd, "hello, 欢迎客户端 id：{$request->fd}\n");
    }
    public function onMessage($ws, $frame){
        echo "信息: {$frame->data}\n";
        foreach ($ws->connections as $fd){
            if($fd == $frame->fd){
                $ws->task([
                    'fd' => $fd,
                    'message' => "我: {$frame->data}",
                ]);
                $ws->push($fd, "我: {$frame->data}");
            }else{
                $ws->push($fd, "对方: {$frame->data}");
            }
        }
        //$ws->push($frame->fd, "server: {$frame->data}");
    }

    //此回调函数在worker进程中执行
//    public function onReceive($ws, $fd, $reactor_id, $data){
//        //投递异步任务
//        $task_id = $ws->task($data);
//        echo "Dispatch AsyncTask: id={$task_id}\n";
//    }

    //处理异步任务(此回调函数在task进程中执行)
    public function onTask ($ws, $task_id, $reactor_id, $data) {
        sleep(10);//
        return $data;//此处return数据到了Finish
    }

    //处理异步任务的结果(此回调函数在worker进程中执行)
    public function onFinish ($ws, $task_id, $data) {
        var_dump("task_id " . $task_id);
        var_dump($data);
    }

    public function onClose($ws, $fd){
        echo "客户端：{$fd} 关闭\n";
    }
}
new WS();